<?php

namespace app\user\controller\user;

use app\BaseController;
use app\user\model\User;
use think\Request;

class Login extends BaseController
{
    /**
     * 小程序用户登录
     */
    public function index(Request $request)
    {
        $code = $request->param()['code'];
        $data['appid'] = "wx8408af83428ec9d1";
        $data['secret'] = "78359bf9534b28fd4e3358a0dca6d080";
        $data['js_code'] = $code;
        $data['grant_type'] = 'authorization_code';
        $userModel = new User();
        $callback = json_decode(http('https://api.weixin.qq.com/sns/jscode2session', $data, 'GET', array("Content-type: text/html; charset=utf-8")), true);
        if (isset($callback['openid'])) {
            $openid = $callback['openid'];
            $isHaveUser = $userModel->getFind(['openid' => $openid], 'id,status');
            if ($isHaveUser) {
                // 是否停用
                if ($isHaveUser['status'] == 2) {
                    return fail([], '状态异常，无法登录');
                }
                // 登录
                $token = getToken('user_id', $isHaveUser['id']);
                $where = ['id' => $isHaveUser['id']];
            } else {
                // 注册
                $insertId = $userModel->getInsert([
                    'itime' => time(),
                    'openid' => $openid,
                ]);
                $token = getToken('user_id', $insertId);
                $where = ['id' => $insertId];
            }
            // 更新token
            $userModel->getUpdate($where, [
                'utime' => time(),
                'token' => $token
            ]);
            return success($token);
        } else {
            return fail([], $callback['errmsg']);
        }
    }
}
